﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.DirectoryServices;
using Auction_Intranet.Models;
using AuctionDataLayer;
using Auction_Intranet.Helpers;
using System.Configuration;

namespace Auction_Intranet.Controllers
{
    [HandleError]
    public class CreateGroupMobileController : ParentController
    {

        DataRepository m_rep = new DataRepository();

        public ActionResult CreateGroupMobile()
        {
            CreateGroupModel model = new CreateGroupModel();
            return View(model);
        }

        [HttpPost, ActionName("CreateGroupMobile")]
        public ActionResult CreateGroupMobile(CreateGroupModel model)
        {
            if (ModelState.IsValid)
            {
                var username = (User.Identity.Name).Split('\\')[1];
                var user = m_rep.GetUserByUsername(username);
                if (user != null)
                {
                    if (model.name == null || model.name == "")
                    {
                        ModelState.AddModelError("name", "Name field is required.");
                    }
                    if (isGroupNameValid(model.name) == false)
                    {
                        ModelState.AddModelError("name", "Group name already aexists");
                    }
                    if (model.addedCredit > user.Balance)
                    {
                        ModelState.AddModelError("addedCredit", "Invalid credit added.");
                    }

                    List<string> members = new List<string>();
                    members.Add(model.groupMember1);
                    members.Add(model.groupMember2);
                    members.Add(model.groupMember3);
                    members.Add(model.groupMember4);
                    members.Add(model.groupMember5);
                    members.Add(model.groupMember6);
                    members.Add(model.groupMember7);
                    members.RemoveAll(checkForNull);

                    if (model.groupMember1 != null || model.groupMember2 != null || model.groupMember3 != null ||
                        model.groupMember4 != null || model.groupMember5 != null || model.groupMember6 != null ||
                        model.groupMember7 != null)
                    {
                        bool checkForDupl = members.Where(x => x == model.groupMember1).Count() > 1;
                        if (model.groupMember1 != null && (!isUsernameValid(model.groupMember1) || checkForDupl))
                        {
                            ModelState.AddModelError("groupMember1", "Invalid member.");
                        }
                        checkForDupl = members.Where(x => x == model.groupMember1).Count() > 1;
                        if (model.groupMember2 != null && (!isUsernameValid(model.groupMember2) || checkForDupl))
                        {
                            ModelState.AddModelError("groupMember2", "Invalid member.");
                        }
                        checkForDupl = members.Where(x => x == model.groupMember1).Count() > 1;
                        if (model.groupMember3 != null && (!isUsernameValid(model.groupMember3) || checkForDupl))
                        {
                            ModelState.AddModelError("groupMember3", "Invalid member.");
                        }
                        checkForDupl = members.Where(x => x == model.groupMember1).Count() > 1;
                        if (model.groupMember4 != null && (!isUsernameValid(model.groupMember4) || checkForDupl))
                        {
                            ModelState.AddModelError("groupMember4", "Invalid member.");
                        }
                        checkForDupl = members.Where(x => x == model.groupMember1).Count() > 1;
                        if (model.groupMember5 != null && (!isUsernameValid(model.groupMember5) || checkForDupl))
                        {
                            ModelState.AddModelError("groupMember5", "Invalid member.");
                        }
                        checkForDupl = members.Where(x => x == model.groupMember1).Count() > 1;
                        if (model.groupMember6 != null && (!isUsernameValid(model.groupMember6) || checkForDupl))
                        {
                            ModelState.AddModelError("groupMember6", "Invalid member.");
                        }
                        checkForDupl = members.Where(x => x == model.groupMember1).Count() > 1;
                        if (model.groupMember7 != null && (!isUsernameValid(model.groupMember7) || checkForDupl))
                        {
                            ModelState.AddModelError("groupMember7", "Invalid member.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "No member added.");
                    }
                    if (ModelState.IsValid && members.Count() != 0)
                    {
                        // create group
                        Group group = new Group();
                        group.Name = model.name;
                        group.Balance = model.addedCredit;
                        group.Created = DateTime.Now;
                        m_rep.AddGroup(group);

                        //Update userbalance 
                        m_rep.UpdateGroupBalance(user.Balance - model.addedCredit, user.MyGroupId);
                        m_rep.UpdateUserBalance(user.Balance - model.addedCredit, user.Id);
                        //Update userSingleGroupBalace
                        m_rep.UpdateUserInGroupSpent(model.addedCredit, user.Id, user.MyGroupId);
                        m_rep.AddUserInGroup(user.Id, group.Id, model.addedCredit);

                        //create invitations
                        ////Get groupMembers need to know how many and they need to be validated
                        foreach (var item in members)
                        {
                            // temporarily if the user is already in the system 
                            // ToDO handle if the user does not exist, create the user in the system and then add invitation
                            // maby the invitation table should have state so if you have acceped or declined it will just not
                            //appear and when coould be marked pending

                            var member = m_rep.GetUserByUsername(item);
                            if (member != null)
                            {
                                m_rep.AddInvitation(member.Id, group.Id);
                            }
                            else
                            {
                                HRStudents_ possibleUser = m_rep.getRUUserByUserName(item);
                                if (possibleUser != null)
                                {
                                    //Create member
                                    User newUser = m_rep.getOrCreateRUUserByUserName(possibleUser.sUser);
                                    m_rep.AddNewUserForAuction(newUser);
                                    //Create a group for this user only  
                                    Group groupNew = new Group();
                                    groupNew.Created = DateTime.Now;
                                    groupNew.Name = newUser.Username;
                                    groupNew.Balance = newUser.Balance;
                                    m_rep.CreateNewSingleGroup(groupNew);
                                    //Add him to his group 
                                    UserInGroup userInGroup = new UserInGroup();
                                    userInGroup.UserId = newUser.Id;
                                    userInGroup.GroupId = groupNew.Id;
                                    userInGroup.CreditAdded = newUser.Balance;
                                    userInGroup.ActiveMember = true;
                                    m_rep.AddMemberToSingleGroup(userInGroup);
                                    m_rep.UpdadeUserSingleGroupId(newUser.Id, groupNew.Id);

                                    //Add invitation
                                    m_rep.AddInvitation(newUser.Id, group.Id);
                                }
                            }
                        }
                        return RedirectToAction("Index", "Groups");
                    }
                    return View(model);
                }
                return View("Error");
            }
            return View(model);
        }

        #region Helpers for controller
        //Helper function for this controller      
        private static bool checkForNull(String s)
        {
            return s == null;
        }

        private bool isGroupNameValid(string name)
        {
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);
            bool exists = m_rep.GetAllGroupNames().Where(x => x == name).SingleOrDefault() != null; ;

            if (user != null && exists == false)
            {
                return true;
            }
            return false;
        }
        private bool isUsernameValid(string member)
        {
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);
            var memberToAdd = m_rep.getRUUserByUserName(member);

            if (user != null && memberToAdd != null)
            {
                if (user.Username != memberToAdd.sUser)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
    }
}
